package com.hp.demo.vteam.action;
/**/
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hp.demo.vteam.base.JsonUtil;
import com.hp.demo.vteam.base.PMF;
import com.hp.demo.vteam.base.annotation.AutoLoad;

public abstract class BaseServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public static final String SUCCESS_MSG = "{\"success\":%s,\"msg\":\"%s\"}";
	public User user;
	public PersistenceManager pm;
	public int start = 0;
	public int limit = 5;
	
	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws IOException {
		doGet(request, response);
	}

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
              throws IOException {
		try{
			UserService userService = UserServiceFactory.getUserService();
			response.setContentType("text/html;charset=utf-8");
			this.user = userService.getCurrentUser();
			if (this.user==null){
				response.sendRedirect(userService.createLoginURL(request.getRequestURI()));
			}
			
	        this.pm = PMF.get().getPersistenceManager();	
			String method = request.getParameter("method");
			if("edit".equals(method)){
				edit(request, response);
			}else if("del".equals(method)){
				del(request, response);
			}if("search".equals(method)){
				String sStart = request.getParameter("start");
				String sLimit = request.getParameter("limit");
			
					if(sStart != null){
						start = Integer.parseInt(sStart);
					}
					//added by wangrenwei begin
					else
					{
						start = 0;
					}
					//added by wangrenwei end
					
					if(sLimit != null){
						limit = Integer.parseInt(sLimit);
					}		
				limit = limit + start;	
				search(request, response);
			}
		}catch (Exception e){
			e.printStackTrace();
			response.getWriter().print(String.format(SUCCESS_MSG, "false","系统异常" ));
		}
		finally
		{
			pm.close();
		}
    }

	
	public void baseEdit(HttpServletRequest request, HttpServletResponse response, Object object)
	    throws Exception{
        	pm.currentTransaction().begin();
            pm.makePersistent(object);      
            pm.currentTransaction().commit();
            pm.flush();
	}
		
	public  <T> void baseSearch(HttpServletRequest request, HttpServletResponse response, Class<T> clz)
		throws Exception{
	    Map<Object, Object> map = new HashMap<Object, Object>();
	    String className = clz.getName();
	    
	    StringBuffer query_str_buffer = new StringBuffer("select from ");
	    query_str_buffer.append(className);
	    //TODO:查询参数策略
	    query_str_buffer.append(" order by addedTime desc ");
	    if(request.getParameter("asPage").equals("true"))
	    {
	    	query_str_buffer.append(" desc range " + start + ", " + limit);
	    }
	    String query = query_str_buffer.toString();
	    
	    List<T> datas = (List<T>) pm.newQuery(query).execute();
	    
	    //As some attribute should be loaded in the request,
	    //I defined this annotation to execute the load by myself.
	    AutoLoad annotation = clz.getAnnotation(AutoLoad.class);
	    if(null != annotation)
	    {
	    	for(String attr : annotation.attrs())
	    	{
	    		String getFuncName = "get" + attr.toUpperCase().charAt(0) + attr.substring(1);
	    		for(Iterator<T> iterator = datas.iterator();iterator.hasNext();)
	    		{
	    			T t = iterator.next();
	    			Method method = clz.getDeclaredMethod(getFuncName);
	    			Object v = method.invoke(t);
	    			pm.refresh(v);
	    		}
	    	}
	    }
	    //
	    map.put("datas", datas);
	    query = "select count(id) from " + className;
	    Integer total = (Integer) pm.newQuery(query).execute();
	    map.put("total", total);
	    response.getWriter().print(JsonUtil.parse2Json(map));
	}
	
	public void baseDel(HttpServletRequest request, HttpServletResponse response, Object object)
	throws Exception{
		pm.currentTransaction().begin();
		
		if(object instanceof Collection)
		{
			for(Iterator iterator = ((Collection)object).iterator();iterator.hasNext();)
			{
				Object subObj = iterator.next();
				pm.deletePersistent(subObj);
			}
		}
		else
		{
			pm.deletePersistent(object);
		}
		pm.currentTransaction().commit();
		pm.flush();
	}
	
	public abstract void edit (HttpServletRequest request, HttpServletResponse response)
    throws Exception;
	
	public abstract void del (HttpServletRequest request, HttpServletResponse response)
    throws Exception;

	public abstract void search (HttpServletRequest request, HttpServletResponse response)
    throws Exception;
}

